package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"test/common"
	"test/model"
)

func FindCourseByCno(ctx *gin.Context) {
	requestcourse := make(map[string]interface{})
	fmt.Println("查询课程执行")
	ctx.ShouldBind(&requestcourse)
	fmt.Println(requestcourse)
	ctx.JSON(http.StatusOK,requestcourse)
}

func Find_allcourse(ctx *gin.Context) {
	var courses []model.Courses
	db := common.GetDB()
	result := db.Find(&courses)
	fmt.Println(courses)
	if result != nil {
		fmt.Println("dada")
	}
	ctx.JSON(http.StatusOK,courses)
}

func DeleteCourse(ctx *gin.Context) {
	DB := common.GetDB()
	fmt.Println("我执行了")
	requeststudent := make(map[string]interface{})
	var courses model.Courses
	//获取参数
	ctx.ShouldBind(&requeststudent)
	fmt.Println(requeststudent["Cno"].(float64),"课号")
	courses.Cno = int(requeststudent["Cno"].(float64))
	DB.Where("cno = ?",courses.Cno).Delete(&courses)
}

func UpdateCourse(ctx *gin.Context) {
	DB := common.GetDB()
	fmt.Println("我是修该课程信息")
	requestUser := make(map[string]interface{})
	//获取参数
	var courses model.Courses
	DB.Last(&courses)
	ctx.ShouldBind(&requestUser)
	courses.Cno = int(requestUser["Cno"].(float64))
	courses.Cname=requestUser["Cname"].(string)
	courses.Cperiod = requestUser["Cperiod"].(string)
	courses.Cclasshour =requestUser["Cclasshour"].(string)
	courses.Cpayment = int(requestUser["Cpayment"].(float64))
	courses.Tno = int(requestUser["Tno"].(float64))
	courses.Cneed = int(requestUser["Cneed"].(float64))
	courses.Cjoin,_ = strconv.Atoi(requestUser["Cjoin"].(string))
	fmt.Println(courses)
	DB.Where("Cno = ?",courses.Cno).Updates(&courses)
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "修改成功",
	})
}

func AddCourse(ctx *gin.Context) {
	DB := common.GetDB()
	requestcourse := make(map[string]interface{})
	//获取参数
	var courses model.Courses
	DB.Last(&courses)
	ctx.ShouldBind(&requestcourse)
	fmt.Println(requestcourse,"我是添加课程")
	cno:=courses.Cno + 1
	cname:= requestcourse["Cname"].(string)
	cperiod:= requestcourse["Cperiod"].(string)
	cclasshour:= requestcourse["Cclasshour"].(string)
	cpayment ,_ := strconv.Atoi(requestcourse["Cpayment"].(string))
	cplace := requestcourse["Cplace"].(string)
	tno,_ := strconv.Atoi(requestcourse["Tno"].(string))
	cneed,_ := strconv.Atoi(requestcourse["Cneed"].(string))
	cjoin,_ := strconv.Atoi(requestcourse["Cjoin"].(string))

	if isCnameExists(DB,cname) {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"学生已经存在"})
		fmt.Println("我执行了")
		return
	}
	newCourse := model.Courses {
		Cno: cno,
		Cname: cname,
		Cperiod: cperiod,
		Cclasshour: cclasshour,
		Cpayment: cpayment,
		Cneed: cneed,
		Cjoin: cjoin,
		Cplace: cplace,
		Tno: tno,
	}
	DB.Create(&newCourse)
	//返回结果
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "添加成功",
	})
}

func isCnameExists(db *gorm.DB,cname string) bool {//string
	var courses model.Courses
	db.Where("cname = ?",cname).First(&courses)
	if courses.Cno != 0 {
		return true
	} else {
		return false
	}
}
